package jee.demo.pro.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 邮箱操作。
 *
 * @author Administrator
 * @version 1.0.0 11-8-16
 */
public class EmailUtils {
    private final static Logger LOGGER = LoggerFactory.getLogger(EmailUtils.class);

    private static boolean SHUTDOWN = false;

    // smtp服务器地址
    //private final static Authenticator authenticator;
    //private final static Properties props = new Properties(); // 获取系统环境
    private static final Address FROM_ADDRESS;
    private static final Session SESSION;

    public static String MAIL_ADDRESS;
    public static String MAIL_PASSWORD;
    public static String MAIL_SMTP_HOST;
    public static boolean MAIL_SMTP_AUTH;
    public static String MAIL_NAME;

    private static final Properties emailProperties = new Properties();
    private static final BlockingQueue<MimeMessage> emailQueue = new LinkedBlockingQueue<>(); // 待发送的邮件队列

    static {
        Authenticator authenticator = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MAIL_ADDRESS, MAIL_PASSWORD);
            }
        };
        Properties props = new Properties();
        props.put("mail.smtp.host", MAIL_SMTP_HOST);
        props.put("mail.smtp.auth", MAIL_SMTP_AUTH);
        SESSION = Session.getDefaultInstance(props, authenticator);

        Address address = null;
        try {
            address = new InternetAddress(MAIL_ADDRESS, MAIL_NAME);
        } catch (UnsupportedEncodingException e) {//ignored
        }
        FROM_ADDRESS = address;

        // start the thread of sending email
        Thread emailThread = new Thread() {
            @Override
            public void run() {
                while (!SHUTDOWN || !emailQueue.isEmpty()) {
                    LOGGER.info("Waiting for email to send!");
                    try {
                        Transport.send(emailQueue.take()); // 发送邮件
                        LOGGER.info("Email sent!");
                    } catch (MessagingException e) {
                        LOGGER.error(e.getMessage());
                    } catch (InterruptedException e) {// ignore
                    }
                }
            }
        };
        emailThread.setDaemon(true);
        emailThread.start();
    }

    public static void init() {
        String classpath = EmailUtils.class.getResource("/").getPath();
        String filename = "email.properties";
        InputStream is = null;
        try {
            is = new FileInputStream(classpath + filename);
            emailProperties.load(is);
            MAIL_SMTP_HOST = (String) emailProperties.get("MAIL_NAME");
            MAIL_ADDRESS = (String) emailProperties.get("MAIL_ADDRESS");
            MAIL_PASSWORD = (String) emailProperties.get("MAIL_PASSWORD");
            MAIL_SMTP_HOST = (String) emailProperties.get("MAIL_SMTP_HOST");
            MAIL_SMTP_AUTH = Boolean.valueOf(String.valueOf(emailProperties.get("MAIL_SMTP_AUTH")));
        } catch (IOException e) {
            LOGGER.info("Resource[{}] not found, using default configuration!", filename);
            MAIL_ADDRESS = "no_reply_j2ee@163.com";
            MAIL_PASSWORD = "j2ee()_+";
            MAIL_SMTP_HOST = "mail.163.com";
            MAIL_SMTP_AUTH = true;
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static MimeMessage getHtmlMessage(String account, String subject, String content) {
        MimeMessage message = new MimeMessage(SESSION);
        try {
            message.setContent(content, "text/html;charset=utf-8"); // 设置邮件内容
            message.setSubject(subject); // 设置邮件主题
            message.setSentDate(new Date()); // 设置邮件发送日期
            message.setFrom(FROM_ADDRESS); // 设置邮件发送者的地址
            Address toAddress = new InternetAddress(account);
            message.addRecipient(Message.RecipientType.TO, toAddress);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return message;
    }

    public static void shutdown(){
        SHUTDOWN = true;
    }
}
